<template>
	<view class="year-calendar">
		<!-- 月视图 -->
		<swiper :current="currentYearIndex" @change="handleYearChange">
			<swiper-item v-for="(year, index) in years" :key="index">
				<view class="year-view">
					<view v-for="item in year.list" :key="item.title"
						:class="{ 'active': item.isSelected, 'today': item.isToday }" @click="selectYear(item)">
						<view class="month">{{ item.title }}</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
	</view>
</template>
<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';

	// 当前年索引
	const currentYearIndex = ref(0);

	// 生成年数据
	const years = ref([]);
	const generateYears = () => {
		const today = new Date();
		const currentYear = today.getFullYear(); // 当前年
		const startYear = currentYear - 2; // 起始年
		years.value = Array.from({
			length: 5
		}, (_, i) => {
			let yearDate = startYear;
			yearDate = startYear + i * 5
			const list = Array.from({
				length: 5
			}, (_, j) => {
				let year = yearDate;
				year += j // 每增加一年
				return {
					title: year, // 月份标题
					isToday: year === currentYear,
					isSelected: year === currentYear
				};
			})
			return {
				list
			}
		});
	};

	// 切换月
	const handleYearChange = (e) => {
		currentYearIndex.value = e.detail.current;
	};
	// 选择日期
	const selectYear = (selectedYear) => {
		years.value = years.value.map((year) => {
			return {
				list: year.list.map((item) => {
					return {
						...item,
						isSelected: item.title === selectedYear.title, // 选中当前日期
					};
				}),
			};

		});
		console.log('选中日期:', selectedYear.title);
	};
	// 初始化生成月数据
	onMounted(() => {
		generateYears();
		console.log(years.value);
	});
</script>
<style lang="scss" scoped>
	.year-calendar {
		height: 80rpx;
		padding: 20rpx;
	}

	.year-view {
		display: flex;
		justify-content: space-between;
		border-radius: 10rpx;
	}

	.year-view>view {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10rpx;

		view {
			line-height: 48rpx;
			text-align: center;
			font-size: 28rpx;
			color: #A6A6A6;
			background: #F9F9F9;
			padding: 2rpx 18rpx;
			border: 1px solid #F9F9F9;
			border-radius: 30rpx;
		}
	}

	.year-view>view.today {
		.month {
			/* 当月样式 */
			border: 1px solid #FF9281;
			background-color: #fff;
		}
	}

	.year-view>view.active {
		.month {
			font-weight: 500;
			font-size: 28rpx;
			color: #fff;
			background: #FF9281;
			border: 1px solid #FF9281;
		}
	}
</style>